package com.pz.gulimall.auth.service;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.pz.gulimall.auth.feign.MemberFeign;
import com.pz.gulimall.auth.vo.User;
import com.pz.gulimall.auth.vo.req.UserLoginReqVo;
import com.pz.gulimall.common.exception.BizCodeEnum;
import com.pz.gulimall.common.exception.RRException;
import com.pz.gulimall.common.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginService {
    @Autowired
    private MemberFeign memberFeign;

    /**TODO
     * 单点登录
     * @param vo
     * @return
     */
    public R singleSingOn(UserLoginReqVo vo) {
        try {
            R ans = memberFeign.queryMember(vo.getId());
            if (ans.getCode() == 0){
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                if(passwordEncoder.matches(vo.getPassword(), String.valueOf(ans.get("pwd")))){
                    StpUtil.login(vo.getId());
                    User user = JSON.to(User.class, ans.get("data"));
                    //存在session的信息
                    StpUtil.getSession().set("user", user);
                    SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
                    Map<String , Object> data = new HashMap<>();
                    data.put("token", tokenInfo);
                    data.put("session", user);
                    return R.ok(BizCodeEnum.AUTH_LOGIN_SUCCESS.getMsg()).put("data", data);
                } else {
                    return R.error(BizCodeEnum.AUTH_LOGIN_FAILED.getCode(), BizCodeEnum.AUTH_LOGIN_FAILED.getMsg());
                }
            }else {
                return R.error(ans.getCode(), ans.getMsg());
            }
        } catch (Exception e) {
            throw new RRException(BizCodeEnum.AUTH_RPC_MEMBER_FAILED, e.getMessage());
        }
    }
}
